package top.naccl.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.naccl.config.UploadConfig;
import top.naccl.service.UploadService;
import top.naccl.util.files.FileUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @description:上传服务实现类
 * @package top.naccl.service.impl
 * @who MiaoMiao "Sprout" BI
 * @date 2021-01-29 09:36:55
 */
@Service
public class UploadServiceImpl implements UploadService {
    @Override
    public String upload(String name,MultipartFile file) throws IOException {
        String imgName = "/" + FileUtils.generateFileName()+ "_" + name;

        SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyyMM");
        //年月作为文件夹
        String dateFolder = sDateFormat.format(new Date());
        //照片文件夹路径
        String imgPath= UploadConfig.path + dateFolder;
        File dir = new File(imgPath);
        if (dir.exists())
        {
            //如果有一个同名文件,则删除文件然后创建文件夹
            if (!dir.isDirectory())
            {
                dir.delete();
                dir.mkdir();
            }
        } else {
            dir.mkdir();
        }
        //照片文件完整路径
        String imgFullPath = imgPath +  imgName;
        FileUtils.write(imgFullPath, file.getInputStream());
        imgName = dateFolder +  imgName;
        return imgName;
    }
}
